package com.mmsj;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.mmsj.pojo.MyUser;
import com.mmsj.service.ApiService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class RetrofitActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        Button btn1 = findViewById(R.id.btn_1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 发送http请求到后台获取所有用户信息：http://127.0.0.1:8080/user/getAllUser
                // 1.创建retrofit的构建器，通过Builder配置基础的URL和解析器
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://192.168.124.2:9292/")  // 基础URL
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                // 2.创建接口实例
                ApiService apiService = retrofit.create(ApiService.class);
                // 3.发送请求
                Call<List<MyUser>> call = apiService.getAllUser();
                // 4.处理请求结果
                call.enqueue(new Callback<List<MyUser>>() {
                    @Override
                    public void onResponse(Call<List<MyUser>> call, retrofit2.Response<List<MyUser>> response) {
                        List<MyUser> list = response.body();
                        for (MyUser user : list) {
                            Log.d("mylog","用户ID : "+user.getId() +
                                                    "用户姓名 : "+ user.getName());
                        }
                        Toast.makeText(RetrofitActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(Call<List<MyUser>> call, Throwable t) {
                        Log.e("mylog", "请求失败");
                    }
                });
            }
        });


    }
}